package blue.http.internal.core.handler.parameter;

import blue.base.core.convert.ConvertService;
import blue.base.core.convert.ConvertServiceFactory;
import blue.base.core.util.JsonUtil;
import blue.http.internal.core.parser.RequestParamConfig;
import blue.validation.core.ValidationUtil;

/**
 * @author Jin Zheng
 * @since 1.0 2021-08-23
 */
public class ParamHandlerUtil {
	private ParamHandlerUtil() {
	}

	/**
	 * parameter validation
	 *
	 * @param config
	 * @param target
	 */
	public static void valid(RequestParamConfig config, Object target) {
		if (target == null || config == null) {
			return;
		}

		if (config.isValidated()) {
			ValidationUtil.valid(target, config.getValidatedGroups());
		}
	}

	/**
	 * parameter validation and convertor
	 *
	 * @param config
	 * @param src
	 * @return
	 */
	public static Object convert(RequestParamConfig config, Object src) {
		if (src == null) {
			return null;
		}

		ConvertService convertService = ConvertServiceFactory.getConvertService();
		if (convertService.canConvert(src.getClass(), config.getParamClazz())) {
			return convertService.convert(src, config.getParamClazz());
		}

		if (src instanceof CharSequence) {
			Object target = JsonUtil.fromString(src.toString(), config.getParamClazz());
			valid(config, target);
			return target;
		}

		return src;
	}

}
